<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/1/9
 * Time: 下午1:04
 */

namespace EasySwoole;

use EasySwoole\Core\Component\SysConst;
use think\Cache;
use think\Db;
use \App\Exception\ExceptionHandler;
use \EasySwoole\Core\AbstractInterface\EventInterface;
use \EasySwoole\Core\Component\Di;
use \EasySwoole\Core\Http\Request;
use \EasySwoole\Core\Http\Response;
use \EasySwoole\Core\Swoole\EventRegister;
use \EasySwoole\Core\Swoole\ServerManager;
use \EasySwoole\Core\Swoole\Process\ProcessManager;
use App\Process\Inotify;
use EasySwoole\Core\Utility\File;

class EasySwooleEvent implements EventInterface
{

    public static function frameInitialize(): void
    {
        // 自动创建所需目录
        File::createDir(EASYSWOOLE_ROOT.'/Temp');
        File::createDir(EASYSWOOLE_ROOT.'/Log');
        File::createDir(EASYSWOOLE_ROOT.'/Public');

        date_default_timezone_set('Asia/Shanghai');
        // 载入所有配置文件目录
        $Conf  = Config::getInstance();
        $Conf->loadPath(EASYSWOOLE_ROOT . '/Conf');
        // 获得数据库配置
        
        $dbConf = $Conf->getConf('database');
        // 全局初始化
        Db::setConfig($dbConf);
        Di::getInstance()->set(SysConst::HTTP_EXCEPTION_HANDLER, ExceptionHandler::class);
        // 获得数据库配置
        $cacheConf = Config::getInstance()->getConf('cache');
        // 全局初始化 cache
        Cache::init($cacheConf);
    }

    public static function mainServerCreate(ServerManager $server, EventRegister $register): void
    {
        // DEBUG 为true 自动打开热重启功能
        // if($Conf  = Config::getInstance()->getConf('DEBUG')){
            // ProcessManager::getInstance()->addProcess('autoReload', Inotify::class);
        // }   
    }

    public static function onRequest(Request $request, Response $response): void
    {
        // TODO: Implement onRequest() method.

        //$response->withAddedHeader('Access-Control-Allow-Origin', 'http://hjk.pd2017.com');
         $response->withAddedHeader('Access-Control-Allow-Origin', 'http://localhost:8010');
        $response->withAddedHeader('Access-Control-Allow-Credentials', 'true');
        $response->withAddedHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        $response->withAddedHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId, Authorization');
        $response->withAddedHeader('Content-type','application/json;charset=utf-8');

        $server  = $request->getSwooleRequest()->server;
        $_SERVER = [];
        if( isset( $server ) ){
            foreach( $server as $key => $value ){
                $_SERVER[strtoupper( $key )] = $value;
            }
        }
    }

    public static function afterAction(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}
